<template>
  <Dialog v-model="dialogVisible" title="申请售后" width="35%">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
    <el-form-item label="子订单号">
        <span>{{formData.orderItemNo}}</span>
    </el-form-item>
    <el-form-item label="售后方式">
        <el-select
          v-model="formData.way"
          class="!w-280px"
          clearable
          placeholder="请选择售后方式"
        >
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_WAY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="售后类型" prop="type">
        <el-select
          v-model="formData.type"
          class="!w-280px"
          clearable
          placeholder="请选择售后类型"
        >
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请数量">
        <el-input-number v-model="formData.applyNum" :min="1" :max="maxTotal" />
      </el-form-item>
      <template v-if="formData.way == 10 || formData.way == 20">
        <el-form-item label="退款金额">
          <el-input-number v-model="formData.refundPrice" :max="maxRefundMoney" /><span>&nbsp;&nbsp;（单位：分）</span>
        </el-form-item>
      </template>
      <el-form-item label="申请原因">
        <el-input type="textarea" style="width: 75%;" rows="3" v-model="formData.applyReason" maxlength="140"  show-word-limit />
      </el-form-item>
      <el-form-item label="凭证图" prop="applyPicUrls">
        <UploadImgs v-model="formData.applyPicUrls" :disabled="isDetail" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" style="width: 75%;" rows="3" v-model="formData.applyDescription" maxlength="140"  show-word-limit/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

</template>
<script lang="ts" setup>
import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'
import * as TradeOrderApi from '@/api/mall/trade/order/index'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'

defineOptions({ name: 'AddAfterSaleForm' })
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const isDetail = ref(false)
const maxTotal = ref(0) // 弹窗的是否展示
const maxRefundMoney = ref(0) //最大退款金额
const formData = ref<AfterSaleApi.AddTradeAfterSale>({
  orderItemId: 0,
  orderItemNo: '',
  way: '10',
  refundPrice: 0,
  memberId:0,
  applyReason: '',
  applyDescription: '',
  applyPicUrls: [],
  interact: false,
  applyNum: 1,
  type: null
})
const formRef = ref() // 表单 Ref

const formRules = {
  feeRate: [{ required: true, message: '请输入渠道费率', trigger: 'blur' }],
  refundPrice: [{ required: true, message: '退款金额不能为空', trigger: 'blur' },
              {min: 1, message: '至少退款1分钱', trigger: 'blur'}
  ],
  applyReason: [{require: true, message: '售后原因不能为空', trigger: 'blur'}],
  way: [{required: true, message: '售后方式不能为空', trigger: 'blur'}],
  type: [{required: true, message: '售后类型不能为空', trigger: 'blur'}],
  applyNum: [{required: true, message: '申请售后数量不能为空', trigger: 'blur'}, {min: 1, message: '申请售后数量至少为1', trigger: 'blur'}]
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
/** 打开弹窗 */
const open = async (row: TradeOrderApi.OrderItemListRespVO) => {
  resetForm()
  maxTotal.value = row.count
  maxRefundMoney.value = row.payPrice
  formData.value.orderItemNo = row.orderItemNo
  formData.value.orderItemId = row.id
  formData.value.applyNum = row.count
  formData.value.refundPrice = row.payPrice
  formData.value.memberId = row.userId
  dialogVisible.value = true
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formRef.value?.resetFields()
  formData.value = {
      orderItemId: 0,
      orderItemNo: '',
      way: '10',
      refundPrice: 0,
      memberId:0,
      applyReason: '',
      applyDescription: '',
      applyPicUrls: [],
      interact: false,
      applyNum: 1,
      type: null
  }
}
const submitForm = async () => {
  if(!formRef) {
    return;
  }
  const valid = await formRef.value.validate()
  if (!valid) return;
   if(formData.value.applyNum > maxTotal.value) {
    message.warning('申请数量不能超过购买数量');
    return;
   }
   AfterSaleApi.createAfterSale(formData.value).then(res => {
    if(res) {
      message.success('申请成功');
      dialogVisible.value = false
      emit('success')
    }
    else {
      message.error('申请失败')
    }
   })
}
</script>